<template>
	<view class="container">
		<!-- 订单基本信息 -->
		<view class="order-basic-info">
			<view class="order-header">
				<text class="order-no">订单号：{{ orderInfo.order_no }}</text>
				<view class="status-badge" :class="getStatusClass[orderInfo.state]">
					{{ getStatusText(orderInfo.state) }}
				</view>
			</view>
		</view>

		<!-- 发货信息表单 -->
		<view class="delivery-form">
			<!-- 快递单号输入 -->
			<view class="form-item">
				<text class="form-label">快递单号</text>
				<uv-input v-model="expressNo" placeholder="请输入快递单号" border="none" clearable
					:customStyle="{ padding: '20rpx', background: '#f8f9fa', borderRadius: '12rpx', fontSize: '28rpx' }">
				</uv-input>
			</view>

			<!-- 发货凭证上传 -->
			<view class="form-item">
				<text class="form-label">发货凭证</text>
				<text class="form-tip">（最多上传6张图片）</text>

				<view class="upload-section">
					<wanl-upload v-model="imageList" :maxCount="6" :multiple="true" uploadText="上传凭证"
						tipText="支持jpg、png格式，大小不超过2M" @upload-success="onUploadSuccess" @upload-error="onUploadError"
						@delete="onImageDelete"></wanl-upload>
				</view>
			</view>
		</view>

		<!-- 底部操作栏 -->
		<view class="bottom-actions">
			<view class="action-btn confirm" :class="{ disabled: !canSubmit }" @click="handleSubmit">
				确认发货
			</view>
		</view>

		<!-- 加载中 -->
		<uv-loading-icon v-if="loading" text="提交中..." mode="circle" size="36"></uv-loading-icon>
	</view>
</template>

<script>
	import wanlUpload from '@/components/wanl-upload/wanl-upload.vue';
	export default {
		components: {
			wanlUpload
		},
		data() {
			return {
				orderId: null,
				loading: false,
				orderInfo: {
					order_no: '',
					state: ''
				},
				expressNo: '',
				imageList: []
			};
		},
		computed: {
			canSubmit() {
				return this.expressNo.trim() !== '' && this.imageList.length > 0;
			}
		},
		onLoad(options) {
			if (options.id) {
				this.orderId = options.id;
				this.loadOrderDetail();
			} else {
				this.$wanlshop.msg('订单ID不存在');
				setTimeout(() => {
					uni.navigateBack();
				}, 1500);
			}
		},
		onBackPress() {
			// 拦截返回按钮，直接返回
			uni.navigateBack();
			return true;
		},
		methods: {
			// 加载订单详情
			async loadOrderDetail() {
				this.loading = true;
				try {
					const res = await uni.$uv.http.get('/supplier/getOrderDetail', {
						params: {
							order_id: this.orderId
						}
					});

					if (res.res.code === 1) {
						this.orderInfo = res.res.data;
					} else {
						this.$wanlshop.msg(res.res.msg || '获取订单详情失败');
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					}
				} catch (error) {
					console.error('获取订单详情失败:', error);
					this.$wanlshop.msg('获取订单详情失败');
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} finally {
					this.loading = false;
				}
			},

			// 上传成功回调
			onUploadSuccess(event) {
				console.log('上传成功:', event);
				const {
					file,
					result,
					index
				} = event;
				this.$wanlshop.msg('上传成功');
			},

			// 上传失败回调
			onUploadError(event) {
				console.error('上传失败:', event);
				const {
					file,
					error,
					index
				} = event;
				this.$wanlshop.msg('上传失败: ' + (error.message || '未知错误'));
			},

			// 删除图片回调
			onImageDelete(event) {
				console.log('删除图片:', event);
				const {
					file,
					index
				} = event;
				this.$wanlshop.msg('删除成功');
			},

			// 获取状态文本
			getStatusText(state) {
				const statusMap = {
					'1': '待付款',
					'2': '待发货',
					'3': '待收货',
					'4': '已收货',
					'5': '已评价',
					'6': '已完成',
					'7': '已取消'
				};
				return statusMap[state] || '未知状态';
			},

			// 获取状态类名
			getStatusClass(state) {
				const classMap = {
					'1': 'status-pending',
					'2': 'status-wait-ship',
					'3': 'status-wait-receive',
					'4': 'status-received',
					'5': 'status-evaluated',
					'6': 'status-completed',
					'7': 'status-cancelled'
				};
				return classMap[state] || 'status-default';
			},

			// 提交发货
			async handleSubmit() {
				if (!this.canSubmit) {
					this.$wanlshop.msg('请填写快递单号并上传发货凭证');
					return;
				}

				// 验证快递单号
				if (this.expressNo.trim().length < 6) {
					this.$wanlshop.msg('请输入正确的快递单号');
					return;
				}

				uni.showModal({
					title: '确认发货',
					content: `确定要发货订单 ${this.orderInfo.order_no} 吗？`,
					success: async (res) => {
						if (res.confirm) {
							await this.submitDelivery();
						}
					}
				});
			},

			// 提交发货请求
			async submitDelivery() {
				this.loading = true;

				try {
					// 获取图片URL数组
					const images = this.imageList.map(item => item.url).join(',');
					const res = await uni.$uv.http.post('/supplier/deliveryOrder', {
						order_id: this.orderId,
						express_no: this.expressNo,
						images: images
					});

					if (res.res.code === 1) {
						this.$wanlshop.msg('发货成功');

						// 返回上一页并刷新
						setTimeout(() => {
							const pages = getCurrentPages();
							const prevPage = pages[pages.length - 2];
							if (prevPage && prevPage.loadData) {
								prevPage.loadData(true);
							}
							uni.navigateBack();
						}, 1500);
					} else {
						this.$wanlshop.msg(res.res.msg || '发货失败');
					}
				} catch (error) {
					console.error('发货失败:', error);
					this.$wanlshop.msg('发货失败，请稍后重试');
				} finally {
					this.loading = false;
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		padding: 30rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
		box-sizing: border-box;
		padding-bottom: 140rpx;
	}

	/* 订单基本信息 */
	.order-basic-info {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

		.order-header {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.order-no {
				font-size: 28rpx;
				font-weight: 600;
				color: #333;
			}

			.status-badge {
				padding: 8rpx 16rpx;
				border-radius: 20rpx;
				font-size: 22rpx;
				font-weight: 500;

				&.status-wait-ship {
					background: #e8f3ff;
					color: #2979ff;
				}
			}
		}
	}

	/* 发货信息表单 */
	.delivery-form {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);

		.form-item {
			margin-bottom: 40rpx;

			.form-label {
				display: block;
				font-size: 28rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 16rpx;
			}

			.form-tip {
				font-size: 24rpx;
				color: #999;
				margin-left: 12rpx;
			}
		}

		.upload-section {
			margin-top: 20rpx;

			// 覆盖 wanl-upload 组件的样式
			.wanl-upload {
				.upload-area {
					.upload-custom {
						width: 160rpx !important;
						height: 160rpx !important;
					}
				}

				.preview-container {
					.image-list {
						.image-item {
							width: 160rpx !important;
							height: 160rpx !important;
						}
					}
				}
			}
		}
	}

	/* 底部操作栏 */
	.bottom-actions {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		padding: 20rpx 30rpx;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.08);

		.action-btn {
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 40rpx;
			font-size: 30rpx;
			font-weight: 500;

			&.confirm {
				background: #2979ff;
				color: #ffffff;

				&.disabled {
					background: #ccc;
					color: #999;
				}
			}
		}
	}
</style>